/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package systole.view.crud.patient;

import java.awt.Frame;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import javax.swing.JDialog;
import systole.domain.clinicalInformation.HabitPatient;

import systole.domain.persons.Medic;
import systole.domain.persons.Patient;
import systole.domain.persons.identityCard.IdentityCard;
import systole.domain.persons.identityCard.IdentityCardType;
import systole.domain.persons.profession.Profession;
import systole.exceptions.ExceptionDAO;
import systole.utils.ImageUtils;
import systole.view.crud.controller.ControllerEntityEdition;
import systole.view.crud.patient.patientComponents.clinicalInfo.ControllerViewClinicalInfoByPatient;
import systole.view.crud.patient.patientComponents.familyBackground.ControllerViewFamilyBackground;
import systole.view.crud.patient.patientComponents.medicines.ControllerViewMedicineByPatient;
import systole.view.crud.patient.patientComponents.pathologies.ControllerViewPathologyByPatient;
import systole.view.crud.patient.patientComponents.sports.ControllerViewSportByPatient;
import systole.view.crud.patient.patientComponents.sugeries.ControllerViewSurgeryByPatient;
import systole.view.messages.EntityDescriptions;

/**
 * 
 * @author jmj
 */
public class ControllerPatientEdition extends ControllerEntityEdition implements WindowListener {

    private ControllerViewClinicalInfoByPatient controllerViewClinicalInfoByPatient;
    private ControllerViewFamilyBackground controllerViewFamilyBackground;
    private ControllerViewMedicineByPatient controllerViewMedicineByPatient;
    private ControllerViewPathologyByPatient controllerViewPathologyByPatient;
    private ControllerViewSportByPatient controllerViewSportByPatient;
    private ControllerViewSurgeryByPatient controllerViewSurgeryByPatient;

    /**
     */
    public ControllerPatientEdition() {
        super();
        this.entityName = EntityDescriptions.PATIENT;
    }

    @Override
    protected String valid() {
        JDialogPatient formToValidate = (JDialogPatient) this.editForm;

        if ((formToValidate.getjEdtName().getText() == null) || (formToValidate.getjEdtName().getText().isEmpty())) {
            return "Debe ingresar el nombre";
        }
        if ((formToValidate.getjEdtSurname().getText() == null) || (formToValidate.getjEdtSurname().getText().isEmpty())) {
            return "Debe ingresar el apellido";
        }

        if ((!formToValidate.getjXEdtBirthdate().isEditValid()) || (formToValidate.getjXEdtBirthdate().getDate() == null)) {
            return "Debe ingresar la edad o fecha de nacimiento";
        }
        return null;
    }

    @Override
    protected void loadEntityOnForm() {
        JDialogPatient formToLoad = (JDialogPatient) this.editForm;
        Patient currentPatient = (Patient) this.curretnEntity;

        formToLoad.getjEdtSurname().setText(currentPatient.getSurname());
        formToLoad.getjEdtName().setText(currentPatient.getName());
        if (currentPatient.getIdentityCard() != null) {
            formToLoad.getjCmbIdentityType().setSelectedItem(
                    currentPatient.getIdentityCard().getCardType());
            formToLoad.getjEdtIdentityNumber().setText(currentPatient.getIdentityCard().getNumber()!=null?
                    currentPatient.getIdentityCard().getNumber().toString():"");
        }
        formToLoad.getjCmbSex().setSelectedItem(currentPatient.getSex());
        formToLoad.getjEdtCellphone().setText(currentPatient.getCellphone());
        formToLoad.getjEdtMail().setText(currentPatient.getEmail());
        formToLoad.getjEdtPhone().setText(currentPatient.getTelephone());
        formToLoad.getjXEdtBirthdate().setDate(currentPatient.getBirthdate());
        formToLoad.getjTxtAge().setText(currentPatient.getAge().toString());
        formToLoad.getDateLastMedicVisit().setDate(currentPatient.getLastMedicVisit());
        formToLoad.getChkUnderObs().setSelected((currentPatient.getUnderMedicalObservation() != null) ? currentPatient.getUnderMedicalObservation().booleanValue() : false);
        formToLoad.getjEdtAddress().setText(currentPatient.getAddress());
        formToLoad.getjEdtCity().setText(currentPatient.getCity());

        if (currentPatient.getProfession() != null) {
            formToLoad.getjCmbProfession().setSelectedItem(currentPatient.getProfession());
        }

        if (currentPatient.getMedic() != null) {
            formToLoad.getCmbHeadPhysician().setSelectedItem(currentPatient.getMedic());
        }

        if (currentPatient.getHabitPatient() != null) {

            formToLoad.getCmbAngryLevel().setSelectedIndex((currentPatient.getHabitPatient().getAngryLevel() != null) ? currentPatient.getHabitPatient().getAngryLevel().intValue() : -1);
            formToLoad.getCmbStressLevel().setSelectedIndex((currentPatient.getHabitPatient().getStressLevel() != null) ? currentPatient.getHabitPatient().getStressLevel().intValue() : -1);
            formToLoad.getChkAutoMedication().setSelected((currentPatient.getHabitPatient().getAutomedication() != null) ? currentPatient.getHabitPatient().getAutomedication().booleanValue() : false);
            formToLoad.getjChkDrink().setSelected((currentPatient.getHabitPatient().getConsummingAlcohol() != null) ? currentPatient.getHabitPatient().getConsummingAlcohol().booleanValue() : false);
            formToLoad.getSpinWalkedSquares().setValue((currentPatient.getHabitPatient().getBlocksWalkedPerDay() != null) ? currentPatient.getHabitPatient().getBlocksWalkedPerDay().intValue() : 0);
            formToLoad.getChkSedentarism().setSelected((currentPatient.getHabitPatient().getSedentary() != null) ? currentPatient.getHabitPatient().getSedentary().booleanValue() : false);
            formToLoad.getTxtWorkplace().setText(currentPatient.getHabitPatient().getWorkPlace() != null ? currentPatient.getHabitPatient().getWorkPlace() : "");
            formToLoad.getjRbNeverSmoke().setSelected((!currentPatient.getHabitPatient().getSmoked().booleanValue()) && (!currentPatient.getHabitPatient().getSmoking().booleanValue()));
            formToLoad.getjRbIsSmoker().setSelected(currentPatient.getHabitPatient().getSmoking().booleanValue());
            formToLoad.getjRbWasSmoker().setSelected(currentPatient.getHabitPatient().getSmoked().booleanValue());
            formToLoad.getjTxtYearsAtStartSmooking().setText(currentPatient.getHabitPatient().getYearsOldAtStart() != null ? currentPatient.getHabitPatient().getYearsOldAtStart().toString() : "");
            formToLoad.getjTxtYearsAtEndSmooking().setText(currentPatient.getHabitPatient().getYearsOldAtFinish() != null ? currentPatient.getHabitPatient().getYearsOldAtFinish().toString() : "");
            formToLoad.getjSpnCigarettsPerDay().setValue((currentPatient.getHabitPatient().getCigarettesPerDay() != null) ? currentPatient.getHabitPatient().getCigarettesPerDay().intValue() : 0);
        }
        formToLoad.intiSmokeHabits();
    }

    @Override
    protected void loadEntityFromForm() {

        Patient patientToLoad = (Patient) this.curretnEntity;
        JDialogPatient formToLoad = (JDialogPatient) this.editForm;

        patientToLoad.setSurname(formToLoad.getjEdtSurname().getText());
        patientToLoad.setName(formToLoad.getjEdtName().getText());

        if (patientToLoad.getIdentityCard() == null) {
            patientToLoad.setIdentityCard(new IdentityCard());

        }

        patientToLoad.getIdentityCard().setCardType(
                (IdentityCardType) formToLoad.getjCmbIdentityType().getSelectedItem());
        try {
            patientToLoad.getIdentityCard().setNumber(
                    Integer.parseInt(formToLoad.getjEdtIdentityNumber().getText()));
        } catch (NumberFormatException e) {
            patientToLoad.getIdentityCard().setCardType(null);
        }
        patientToLoad.setSex((String) formToLoad.getjCmbSex().getSelectedItem());
        formToLoad.getjCmbSex().setSelectedItem(patientToLoad.getSex());
        patientToLoad.setCellphone(formToLoad.getjEdtCellphone().getText());
        patientToLoad.setEmail(formToLoad.getjEdtMail().getText());
        patientToLoad.setTelephone(formToLoad.getjEdtPhone().getText());
        patientToLoad.setBirthdate(formToLoad.getjXEdtBirthdate().getDate());
        patientToLoad.setMedic((Medic) formToLoad.getCmbHeadPhysician().getSelectedItem());
        patientToLoad.setLastMedicVisit(formToLoad.getDateLastMedicVisit().getDate());
        patientToLoad.setUnderMedicalObservation(formToLoad.getChkUnderObs().isSelected());
        patientToLoad.setAddress(formToLoad.getjEdtAddress().getText());
        patientToLoad.setCity(formToLoad.getjEdtCity().getText());

        patientToLoad.setProfession((Profession) formToLoad.getjCmbProfession().getSelectedItem());

        if (patientToLoad.getHabitPatient() == null) {
            patientToLoad.setHabitPatient(new HabitPatient(patientToLoad));
        }

        patientToLoad.getHabitPatient().setAngryLevel(formToLoad.getCmbAngryLevel().getSelectedIndex());
        patientToLoad.getHabitPatient().setStressLevel(formToLoad.getCmbStressLevel().getSelectedIndex());
        patientToLoad.getHabitPatient().setAutomedication(formToLoad.getChkAutoMedication().isSelected());
        patientToLoad.getHabitPatient().setConsummingAlcohol(formToLoad.getjChkDrink().isSelected());
        patientToLoad.getHabitPatient().setBlocksWalkedPerDay((Integer) formToLoad.getSpinWalkedSquares().getValue());
        patientToLoad.getHabitPatient().setSedentary(formToLoad.getChkSedentarism().isSelected());
        patientToLoad.getHabitPatient().setSmoking(formToLoad.getjRbIsSmoker().isSelected());
        patientToLoad.getHabitPatient().setSmoked(formToLoad.getjRbWasSmoker().isSelected());

        if ((patientToLoad.getHabitPatient().getSmoked()) || (patientToLoad.getHabitPatient().getSmoking())) {

            patientToLoad.getHabitPatient().setCigarettesPerDay((Integer) formToLoad.getjSpnCigarettsPerDay().getValue());

            Integer years;

            try {
                years = new Integer((formToLoad.getjTxtYearsAtStartSmooking().isEditValid()) ? formToLoad.getjTxtYearsAtStartSmooking().getText() : "0");
            } catch (NumberFormatException e) {
                years = 0;
            }
            patientToLoad.getHabitPatient().setYearsOldAtStart(years);

            if (patientToLoad.getHabitPatient().getSmoked()) {

                try {
                    years = new Integer((formToLoad.getjTxtYearsAtEndSmooking().isEditValid()) ? formToLoad.getjTxtYearsAtEndSmooking().getText() : "0");
                } catch (NumberFormatException e) {
                    years = 0;
                }
                patientToLoad.getHabitPatient().setYearsOldAtFinish(years);
            }

        } else {
            patientToLoad.getHabitPatient().setCigarettesPerDay(0);
            patientToLoad.getHabitPatient().setYearsOldAtStart(0);
            patientToLoad.getHabitPatient().setYearsOldAtFinish(0);
        }
        patientToLoad.setLastUpdate(Calendar.getInstance());
        patientToLoad.getHabitPatient().setWorkPlace(formToLoad.getTxtWorkplace().getText());
    }

    @Override
    protected void save() throws ExceptionDAO {
            this.facadeDB.getPatientBroker().update(
                    (Patient) this.curretnEntity);
    }

    /**
     * @return the controllerViewClinicalInfoByPatient
     */
    public ControllerViewClinicalInfoByPatient getControllerViewClinicalInfoByPatient() {
        return controllerViewClinicalInfoByPatient;
    }

    /**
     * @return the controllerViewFamilyBackground
     */
    public ControllerViewFamilyBackground getControllerViewFamilyBackground() {
        return controllerViewFamilyBackground;
    }

    /**
     * @return the controllerViewMedicineByPatient
     */
    public ControllerViewMedicineByPatient getControllerViewMedicineByPatient() {
        return controllerViewMedicineByPatient;
    }

    /**
     * @return the controllerViewPathologyByPatient
     */
    public ControllerViewPathologyByPatient getControllerViewPathologyByPatient() {
        return controllerViewPathologyByPatient;
    }

    /**
     * @return the controllerViewSportByPatient
     */
    public ControllerViewSportByPatient getControllerViewSportByPatient() {
        return controllerViewSportByPatient;
    }

    /**
     * @return the controllerViewSurgeryByPatient
     */
    public ControllerViewSurgeryByPatient getControllerViewSurgeryByPatient() {
        return controllerViewSurgeryByPatient;
    }

    public void windowClosing(WindowEvent e) {
        if (!this.isChangesCommitted()) {
            this.cancel();
        }
    }

    public void windowClosed(WindowEvent e) {
    }

    public void windowIconified(WindowEvent e) {
    }

    public void windowDeiconified(WindowEvent e) {
    }

    public void windowActivated(WindowEvent e) {
    }

    public void windowDeactivated(WindowEvent e) {
    }

    public void windowOpened(WindowEvent e) {
    }

    @Override
    protected void loadIconOnForm() {
        this.editForm.setIconImage(ImageUtils.buildImage("resources/icons/medic/Patient16.png"));
    }

    @Override
    protected Object createEntity() throws ExceptionDAO {
        Patient patient = new Patient();
        patient.setSurname("");
        patient.setName("");
        this.facadeDB.getPatientBroker().insert(patient);
        return patient;
    }

    @Override
    protected JDialog createEditionForm(Frame parent) {
        JDialogPatient form = new JDialogPatient(parent, this);
        form.addWindowListener(this);
        return form;
    }

    @Override
    protected void initFormsControls() throws ExceptionDAO {
        JDialogPatient patientForm = (JDialogPatient) this.editForm;
        this.controllerViewClinicalInfoByPatient = new ControllerViewClinicalInfoByPatient(patientForm.getTableClinicalInfo(), (Patient) this.curretnEntity, this.isEditing());
        this.controllerViewFamilyBackground = new ControllerViewFamilyBackground(patientForm.getjTableBackground(), (Patient) this.curretnEntity, this.isEditing());
        this.controllerViewMedicineByPatient = new ControllerViewMedicineByPatient(patientForm.getTableMedicinesList(), (Patient) this.curretnEntity, this.isEditing());
        this.controllerViewPathologyByPatient = new ControllerViewPathologyByPatient(patientForm.getTablePathologiesList(), (Patient) this.curretnEntity, this.isEditing());
        this.controllerViewSportByPatient = new ControllerViewSportByPatient(patientForm.getTableSportsList(), (Patient) this.curretnEntity, this.isEditing());
        this.controllerViewSurgeryByPatient = new ControllerViewSurgeryByPatient(patientForm.getTableSurgeriesList(), (Patient) this.curretnEntity, this.isEditing());

        //Cargo el combo con la lista documentos
        patientForm.getjCmbIdentityType().removeAllItems();
        List<IdentityCardType> identityCardTypes = this.facadeDB.getIdentityCardBroker().getAllIdentityCardTypes();
        Iterator<IdentityCardType> itCardType = identityCardTypes.iterator();
        while (itCardType.hasNext()) {
            patientForm.getjCmbIdentityType().addItem(itCardType.next());
        }

        //Cargo el combo con la lista de los posibles médicos
        patientForm.getCmbHeadPhysician().removeAllItems();

        List<Medic> medics = this.facadeDB.getMedicBroker().getAllMedics();
        Iterator<Medic> itMedic = medics.iterator();
        while (itMedic.hasNext()) {
            patientForm.getCmbHeadPhysician().addItem(itMedic.next());
        }

        //Cargo el combo con la lista de profesiones
        patientForm.getjCmbProfession().removeAllItems();
        List<Profession> professions = this.facadeDB.getProfessionBroker().getAllProfessions();
        Iterator<Profession> itProf = professions.iterator();
        while (itProf.hasNext()) {
            patientForm.getjCmbProfession().addItem(itProf.next());
        }

        this.editForm = patientForm;
    }
}
